package com.college.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.college.authority.service.UmsMenuService;
import com.college.authority.service.UmsRoleMenuRelationService;
import com.college.authority.mapper.UmsMenuMapper;
import com.college.common.pojo.ao.UmsMenu;
import com.college.common.pojo.ao.UmsRoleMenuRelation;
import com.college.common.pojo.dto.umsMenu.UmsMenuNode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 后台菜单管理Service实现类
 * Created by macro on 2020/2/2.
 */
@Service
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements UmsMenuService {
	@Autowired
	private UmsMenuMapper menuMapper;
	@Autowired
	private UmsRoleMenuRelationService menuRelationService;

	@Override
	public boolean create(UmsMenu umsMenu) {
		return save(umsMenu);
	}

	@Override
	public boolean update(UmsMenu umsMenu) {
		return updateById(umsMenu);
	}

	@Override
	public Page<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
		Page<UmsMenu> page = new Page<>(pageNum, pageSize);
		QueryWrapper<UmsMenu> wrapper = new QueryWrapper<>();
		if (parentId != null) {
			wrapper.lambda().eq(UmsMenu::getParentId, parentId)
					.orderByDesc(UmsMenu::getSort);
		}
		return page(page, wrapper);
	}

	@Override
	public List<UmsMenu> treeList() {
		return menuMapper.getAllMenuList();
	}

	/**
	 * 将UmsMenu转化为UmsMenuNode并设置children属性
	 */
	private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
		UmsMenuNode node = new UmsMenuNode();
		BeanUtils.copyProperties(menu, node);
		List<UmsMenuNode> children = menuList.stream()
				.filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
				.map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
		node.setChildren(children);
		return node;
	}

	@Override
	public Boolean removeMenu(Long mid) {
		// 通过父级编号
		List<Long> idWithChild = menuMapper.getIdWithChild(mid);
		return menuRelationService.lambdaUpdate().in(UmsRoleMenuRelation::getMenuId, idWithChild).remove() & this.lambdaUpdate().in(UmsMenu::getId, idWithChild).remove();
	}
}
